package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏西西
 * Date: 2023-09-05
 * Time: 15:46
 */
class MyBlockingQueue1{
    private int[] items= new int[1000];
    private int tail = 0;
    private int head = 0;
    private int size = 0;

    //入队列
    public void put(int value) throws InterruptedException {
        synchronized (this) {
            while(size == items.length){
                //return;
                this.wait();
            }
            items[tail] = value;
            tail ++;
            if(tail >= items.length ){
                tail = 0;
            }
            //这个notify唤醒的是take的wait
            this.notify();
            size++;
        }
    }

    //出队列

    public Integer take() throws InterruptedException {
        int result = 0;
        synchronized (this) {
            while(size == 0){
               // return null;
                this.wait();
            }
             result =items[head];
            head++;

            if(head >= items.length){
                head = 0;
            }
            size--;

            //唤醒put中的wait;
            this.notify();
        }
        return result;
    }
}
public class ThreadD23 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue();
        queue.put(1);
        queue.put(2);
        queue.put(3);
        queue.put(4);
        int result = queue.take();
        System.out.println("result = "+result);
        result = queue.take();
        System.out.println("result = "+result);
        result = queue.take();
        System.out.println("result = "+result);
        result = queue.take();
        System.out.println("result = "+result);

    }
}
